package com.redpack.redpost.util.to;

import java.io.BufferedInputStream;
import java.io.ByteArrayInputStream;
import java.io.OutputStream;
import java.net.URL;
import java.net.URLConnection;

import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPReply;

public class FileUpload {
 
    private FileUpload () {
        
    }
    
    public static boolean creaArchivoEnSpool ( String cadena , int suc , int id_fact  )
            throws
                Exception
    {
        boolean res = false ;
        System.out.println("::::::: Entro a inicio");
        String baseNombre = "" ;
        String filename = ""+ baseNombre + "" + suc + "_" + id_fact + ".spl" ;
        String filename2 = filename.substring(0 , filename.indexOf(".") ) ; 
        String user = "anonymous" ,
        pass = "",
        server = "192.168.5.51",
        remotePath = "/pub/PruebasSpoolTienda/" + filename ;
        
        //  URL-----------------
        
        try {            
            URL url = new URL("ftp://" + user + ":" + pass + "@" + server + remotePath + ";type=i");
            URLConnection urlc = url.openConnection();
            OutputStream os = urlc.getOutputStream();
            BufferedInputStream input = new BufferedInputStream( new ByteArrayInputStream( cadena.getBytes( ) ) ) ;
            byte[] buffer = new byte[2084] ;
            int bytesRead = 0 ;
            while ( (bytesRead = input.read(buffer) ) != -1 ) {
            os.write(buffer,0,bytesRead);
            }
            os.flush();            
            os.close();    
            input.close();
            String f = url.getFile() ;
            System.out.println(f);
            

            FTPClient ftp = new FTPClient() ;
            ftp.connect(server);
            ftp.login(user, pass);
            if(FTPReply.isPositiveCompletion(ftp.getReplyCode())){
                ftp.setFileType(FTPClient.ASCII_FILE_TYPE);
                ftp.cwd("/pub/PruebasSpoolTienda/");
               res = ftp.rename( filename , "" + filename2 + ".txt" ) ;
                ftp.disconnect();
            }
            
//            FtpClient ftp = new FtpClient( server ) ;
//            ftp.login(user, pass) ;
//            ftp.cd( "/pub/PruebasSpoolTienda/" ) ;
//            ftp.rename(filename, "nuevo3.txt") ;
//            ftp.closeServer() ;
            
            
            } catch (Exception ex) {
            ex.printStackTrace();
            return res ;            
            }
        return res ;
    }

}